package archer.framework.utils;

import archer.framework.client.config.RemoteFileServerConfig;
import archer.framework.client.result.MapExecuteResult;
import archer.framework.protocol.result.ExecuteResult;

import static archer.framework.protocol.result.ExecuteResultProcessor.*;

import jodd.bean.BeanUtil;
import jodd.http.up.ByteArrayUploadable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author christ
 * @date 2016/8/17
 */
public class RemoteFileServerUtils {

    private static final Logger logger = LoggerFactory.getLogger(RemoteFileServerUtils.class);

    /**
     * 获得文件id
     *
     * @param result
     * @return
     */
    public static String getFileId(ExecuteResult result) {

        return BeanUtil.pojo.getProperty(result, "resultData.id");
    }

    /**
     * 获得文件存储路径
     *
     * @param result
     * @return
     */
    public static String getFilePath(ExecuteResult result) {

        return BeanUtil.pojo.getProperty(result, "resultData.path");
    }

    /**
     * 获得文件名称
     *
     * @param result
     * @return
     */
    public static String getFileName(ExecuteResult result) {

        return BeanUtil.pojo.getProperty(result, "resultData.filename");
    }

    /**
     * 获得文件大小
     *
     * @param result
     * @return
     */
    public static String getFileSize(ExecuteResult result) {

        return BeanUtil.pojo.getProperty(result, "resultData.size");
    }

    /**
     * 上传
     *
     * @param url
     * @param file
     * @return
     */
    public static ExecuteResult upload(String url, MultipartFile file) {

        try {

            if (ValidateUtils.isEmpty(file) || ValidateUtils.isEmpty(file.getBytes())) {

                return paramInvalidate("文件不能为空");
            }

            ByteArrayUploadable upload = new ByteArrayUploadable(file.getBytes(), file.getOriginalFilename());

            return toExecuteResult(HttpUtils.post(config().getHost() + url, MapUtils.asMap("file", upload)));

        } catch (IOException e) {

            logger.error("文件上传>>文件流读取错误", e);

            return paramInvalidate("文件读取错误，请检查");
        }


    }

    private static ExecuteResult toExecuteResult(String json) {

        MapExecuteResult mapExecuteResult = JSONUtils.deserialize(json, MapExecuteResult.class);

        return mapExecuteResult.cast();
    }

    /**
     * 获得文件服务器配置
     *
     * @return
     */
    private static RemoteFileServerConfig config() {

        return RemoteFileServerConfig.instance();
    }
}
